<?php

/**
 * View Helper
 * Help construction of basic 'view' in a MVC
 */
class View_Helper {
	
	/**
	 * Include a view, with params
	 * includeview("view.php","nameparam1","value1","nameparam2","value2", ...)
	 */
	public static function includeview($path) {
		$args = func_get_args();
		$params = array();
		
		array_shift($args);
		for ($i = 0; $i < count($args); $i+=2) {
			$name = $args[$i];
			$value = $args[$i+1];
			$params[$name] = $value;
		}
		self::displayview($path, $params);
	}
	
	/**
	 * Display a view
	 */
	public static function displayview($path, $params = array(), $output = true) {
		
		ob_start();
		$befglobals = array();
		$globalsToDelete = array();
		foreach ($params as $name => $value) {
			if (isset($GLOBALS[$name])) {
				$befglobals[$name] = $value;
			}
			else {
				$globalsToDelete[] = $name;
			}
			$GLOBALS[$name] = $value;
		}
		
		foreach ($GLOBALS as $name => $value) {
			$$name = $value;
		}
		
		include($path);
		
		foreach ($befglobals as $name => $value) {
			$GLOBALS[$name] = $value;
			$$name = $value;
		}
		foreach ($globalsToDelete as $name) {
			unset($$name);
			unset($GLOBALS[$name]);
		}
		
		
		if (!$output) {
			return ob_get_clean();
		}
		else {
			ob_end_flush();
		}
	}
	
	/**
	 * Get the value, or the default value if not set
	 */
	public static function defval($var, $default) {
		$val = $var;
		if (!isset($var)) {
			$val = $default;
		}
		return $val;
	}
	
}

/**
 * View_Helper::includeview
 */
function includeview($path) {
	$args = func_get_args();
	call_user_func_array(array('View_Helper', 'includeview'), $args);
}

/**
 * View_Helper::defval
 */
function defval($var, $default) {
	return View_Helper::defval($var, $default);
}
